home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C04 / CLib.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.8 KB  |  66 lines

  1. //: C04:CLib.cpp {O}
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Implementation of example C-like library
  7. // Declare structure and functions:
  8. #include "CLib.h"
  9. #include <iostream>
  10. #include <cassert> 
  11. using namespace std;
  12. // Quantity of elements to add
  13. // when increasing storage:
  14. const int increment = 100;
  15.  
  16. void initialize(CStash* s, int sz) {
  17.   s->size = sz;
  18.   s->quantity = 0;
  19.   s->storage = 0;
  20.   s->next = 0;
  21. }
  22.  
  23. int add(CStash* s, const void* element) {
  24.   if(s->next >= s->quantity) //Enough space left?
  25.     inflate(s, increment);
  26.   // Copy element into storage,
  27.   // starting at next empty space:
  28.   int startBytes = s->next * s->size;
  29.   unsigned char* e = (unsigned char*)element;
  30.   for(int i = 0; i < s->size; i++)
  31.     s->storage[startBytes + i] = e[i];
  32.   s->next++;
  33.   return(s->next - 1); // Index number
  34. }
  35.  
  36. void* fetch(CStash* s, int index) {
  37.   // Check index boundaries:
  38.   assert(0 <= index && index < s->next);
  39.   // Produce pointer to desired element:
  40.   return &(s->storage[index * s->size]);
  41. }
  42.  
  43. int count(CStash* s) {
  44.   return s->next;  // Elements in CStash
  45. }
  46.  
  47. void inflate(CStash* s, int increase) {
  48.   assert(increase > 0);
  49.   int newQuantity = s->quantity + increase;
  50.   int newBytes = newQuantity * s->size;
  51.   int oldBytes = s->quantity * s->size;
  52.   unsigned char* b = new unsigned char[newBytes];
  53.   for(int i = 0; i < oldBytes; i++)
  54.     b[i] = s->storage[i]; // Copy old to new
  55.   delete [](s->storage); // Old storage
  56.   s->storage = b; // Point to new memory
  57.   s->quantity = newQuantity;
  58. }
  59.  
  60. void cleanup(CStash* s) {
  61.   if(s->storage != 0) {
  62.    cout << "freeing storage" << endl;
  63.    delete []s->storage;
  64.   }
  65. } ///:~
  66.